package org.uim.cricket.storage;

import java.io.*;
import java.util.List;

public class FileQueryStringFetcher implements QueryStringFetchable {

	private String[] files = null;
	
	public FileQueryStringFetcher() {
		
	}
	
	public FileQueryStringFetcher(String theFile) {
		files = new String[1];
		files[0] = theFile;
	}
	
	public FileQueryStringFetcher(String[] theFiles) {
		this.files = theFiles;
	}
	
	@Override
	public List<String> fetchQueries() throws Exception {
		return null;
	}

	@Override
	public void executeQueries(QueryExecutable qexec) throws Exception {
		if (files == null) {
			Dlogger.debug(" No query files found!");
			return;
		}
		
		for (int i=0; i<files.length; i++) {
			File f = new File(files[i]);
			if (!f.exists()) {
				Dlogger.debug("  Query file doesn't exist! ['" + files[i] + "']");
				continue;
			}
			
			Dlogger.debug("   - Processing query file: '" + files[i] + "'..."); 
			this.execSingleFile(files[i], qexec);
			Dlogger.debug("      Completed" );
		}
	}
	
	private void execSingleFile(String file, QueryExecutable qexec) throws Exception {
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String line = null;
		
		while ((line = reader.readLine()) != null) {
			if (line.length() == 0) continue;
			
			if (line.startsWith("--")) {
				Dlogger.debug(" --> processing queries for match " + line);
				continue;
			}
			if (line.length() == 0) continue;
			
			try {
				qexec.executeQuery(line);
			} catch (Exception ex) {
				Dlogger.error(" Error executing: " + line);
				System.out.println(line);
				Dlogger.error("Error is: ", ex);
				
				if (StorageProperties.getBoolValue("interrupt.on.error")) {
					throw ex;
				}
			}
		}
	}

	@Override
	public void setParameters(String[] args) {
		this.files = args;
	}

}
